//
//  DiagnosisCameraViewModel.m
//  MobileChecker
//
//  Created by ehanxuan on 2015/01/27.
//  Copyright (c) 2015年 Lymons. All rights reserved.
//

#import "DiagnosisCameraViewModel.h"
#import "CameraDiagnosisService.h"

#import <MobileCoreServices/UTCoreTypes.h>
#import <AssetsLibrary/AssetsLibrary.h>

@interface DiagnosisCameraViewModel () <UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (strong, nonatomic) UIImagePickerController *cameraDevicePicker;
@property (strong, nonatomic) id<RACSubscriber> subscriber;

@end
@implementation DiagnosisCameraViewModel

- (instancetype)init
{
    return [super initWithServices:[[CameraDiagnosisService alloc] init]];
}

- (void)initialize
{
    [super initialize];
    self.enableCheck = [CheckResultUserDefaults standardUserDefaults].cameraCheckResult == DiagnosisCheckResultNoCheck;
    self.headerString = @"写真を撮り、画像の状態を確認してください。\n画面をタップすると、開始します。";
    self.checkingCameraDevice = MCCameraDeviceUnknown;
}

- (void)resultDidReceived:(DiagnosisCheckResult)result
{
    [super resultDidReceived:result];
    [CheckResultUserDefaults standardUserDefaults].cameraCheckResult = result;
}

#pragma mark - view
- (UIImagePickerController *)cameraDevicePicker
{
    if (_cameraDevicePicker == nil) {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        NSArray *mediatypes = [UIImagePickerController availableMediaTypesForSourceType:sourceType];
        if([UIImagePickerController isSourceTypeAvailable:sourceType] && [mediatypes count] > 0) {
            NSArray *mediatypes = [UIImagePickerController availableMediaTypesForSourceType:sourceType];
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.sourceType = sourceType;
            picker.mediaTypes=mediatypes;
            picker.allowsEditing = NO;
            NSString *requiredmediatype = (NSString *)kUTTypeImage;
            NSArray *arrmediatypes = [NSArray arrayWithObject:requiredmediatype];
            [picker setMediaTypes:arrmediatypes];
            
            _cameraDevicePicker = picker;
            
        } else {
            _cameraDevicePicker = nil;
        }
    }
    
    return _cameraDevicePicker;
}

- (UIImagePickerController *)cameraDeviceRear
{
    BOOL isRearSupport = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
    if (!isRearSupport) {
        return nil;
    }
    
    UIImagePickerController *cameraPicker = self.cameraDevicePicker;
    cameraPicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    
    return cameraPicker;
}

- (UIImagePickerController *)cameraDeviceFront
{
    BOOL isFrontSupport = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
    if (!isFrontSupport) {
        return nil;
    }
    
    UIImagePickerController *cameraPicker = self.cameraDevicePicker;
    cameraPicker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    
    return cameraPicker;
}

- (UIView *)imagePreviewView:(UIImage *)image
{
    UIView *imageBackgroundView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    imageBackgroundView.backgroundColor = [UIColor blackColor];
    CGSize imageSize = [self imageSize:image];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imageSize.width, imageSize.height)];
    imageView.center = imageBackgroundView.center;
    imageView.image = image;
    [imageBackgroundView addSubview:imageView];
    
    return imageBackgroundView;
}

- (CGSize)imageSize:(UIImage *)image
{
    CGSize imageSize = image.size;
    CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    
    float widthScale = screenSize.width / imageSize.width;
    float heightScale = screenSize.height / imageSize.height;
    
    float scale = widthScale <= heightScale ? widthScale : heightScale;
    
    CGSize size = CGSizeMake(imageSize.width * scale, imageSize.height * scale);
    
    return size;
}


#pragma mark - camera operation

- (BOOL)hasCameraDevice
{
    BOOL isRearSupport = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
    BOOL isFrontSupport = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
    
    return isRearSupport || isFrontSupport;
}

- (RACSignal *)openCameraDevice:(MCCameraDevice)cameraDevice
{
    if (cameraDevice == MCCameraDeviceUnknown) {
        self.checkingCameraDevice = MCCameraDeviceUnknown;
        [self.subscriber sendCompleted];
        return nil;
    }
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        self.subscriber = subscriber;
        
        switch (cameraDevice) {
            case MCCameraDeviceRear:
                [self openCameraDevice];
                break;
                
            case MCCameraDeviceFront:
                [self openCameraDeviceFront];
                break;
                
            default:
                break;
        }
        
        return [RACDisposable disposableWithBlock:^{
            
        }];
    }];
}

- (BOOL)openCameraDevice
{
    if (![self hasCameraDevice]) {
        return NO;
    }
    
    if ([self openCameraDeviceRear]) {
        return YES;
    }
    
    if ([self openCameraDeviceFront]) {
        return YES;
    }
    
    [self.subscriber sendError:nil];
    
    return NO;
}

- (BOOL)openCameraDeviceRear
{
    UIImagePickerController *cameraPicker = self.cameraDeviceRear;
    if (cameraPicker) {
        cameraPicker.delegate = self;
        [self.subscriber sendNext:cameraPicker];
        return YES;
    }
    
    return NO;
}

- (BOOL)openCameraDeviceFront
{
    UIImagePickerController *cameraPicker = self.cameraDeviceFront;
    if (cameraPicker) {
        cameraPicker.delegate = self;
        [self.subscriber sendNext:cameraPicker];
        return YES;
    }
    
    return NO;
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    BOOL isFrontSupport = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
    
    UIImage* originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIView *imageView = [self imagePreviewView:originalImage];

    switch (picker.cameraDevice) {
        case UIImagePickerControllerCameraDeviceRear:
            self.checkingCameraDevice = MCCameraDeviceRear;
            break;
            
        case UIImagePickerControllerCameraDeviceFront:
            self.checkingCameraDevice = MCCameraDeviceFront;
            break;
            
        default:
            self.checkingCameraDevice = MCCameraDeviceUnknown;
            break;
    }
    [self.subscriber sendNext:imageView];
    
    if (isFrontSupport) {
        [picker dismissViewControllerAnimated:NO completion:NULL];
    } else {
        [picker dismissViewControllerAnimated:YES completion:NULL];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        self.checkingCameraDevice = MCCameraDeviceUnknown;
        [self.subscriber sendCompleted];
    }];
}

@end
